package CustomClassFile.yueli;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import CustomClassFile.CronJob.DateUtil;
import CustomClassFile.CronJob.Pbzxx;
import weaver.conn.RecordSet;

public class KaoqinDk_Sanban {
	public static final Log logger = LogFactory.getLog(KaoqinDk_Sanban.class);

	// 插入打卡信息
	/**
	 * 
	 * @param curruserid
	 * @param kqrq
	 * @param kqsj
	 * @param kqdd
	 * @param kqdjwd
	 * @param kqdkjd
	 * @param kqdkwd
	 * @param curraddress
	 * @param formmodeid
	 * @param modedatacreater
	 * @param modedatacreatertype
	 * @param modedatacreatedate
	 * @param modedatacreatetime
	 * @param kqlx
	 * @param pbsj
	 * @param sbxb
	 * @param kqdbh
	 * @param bcbh
	 * @param isflow
	 * @param dkcard
	 * @param dkcardstatus
	 * @param flowdataid
	 * @return
	 */
	public static boolean insertDaKa(String curruserid, String kqrq, String kqsj, String kqdd, String kqdjwd,
			String kqdkjd, String kqdkwd, String curraddress, String formmodeid, String modedatacreater,
			String modedatacreatertype, String modedatacreatedate, String modedatacreatetime, String kqlx, String pbsj,
			String sbxb, String kqdbh, String bcbh, String isflow, String dkcard, String dkcardstatus,
			String flowdataid,String day) {
		formmodeid = "2";
		modedatacreater = curruserid;
		modedatacreatertype = "0";
		modedatacreatedate = DateUtil.getCurrentDateTime("yyyy-MM-dd");
		modedatacreatetime = DateUtil.getCurrentDateTime("HH:mm:ss");

		// 查询eid
		String sqleid = "select lastname,outkey from hrmresource where id=?";
		String eid = "";
		String name = "";
		RecordSet rseid = new RecordSet();
		rseid.executeQuery(sqleid, curruserid);

		if (rseid.next()) {
			eid = rseid.getString("outkey");
			name = rseid.getString("lastname");
		}
		RecordSet isdk = new RecordSet();
		String sqlisdk="select * from uf_kqxx where kqry=? and pbrq=? and dkcard=?";
		isdk.executeQuery(sqlisdk,curruserid,day,dkcard);
		if(isdk.next()) {
			return true;
		}
		
		RecordSet rs = new RecordSet();
		String sql = "insert into uf_kqxx (kqry,kqrq,kqsj,kqdd,kqdjwd,kqdkjd,kqdkwd,kqrdkdd,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,kqlx,pbsj,sbxb,kqdbh,bcbh,isflow,dkcard,dkcardstatus,flowdataid,eid,pbrq) "
				+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		boolean flag = rs.executeUpdate(sql, curruserid, kqrq, kqsj, kqdd, kqdjwd, kqdkjd, kqdkwd, curraddress,
				formmodeid, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime, kqlx, pbsj,
				sbxb, kqdbh, bcbh, isflow, dkcard, dkcardstatus, flowdataid, eid,day);
		if (flag) {
			if ("JiaBan".equals(bcbh)) {// 如果是节假日加班
				if ("card1".equals(dkcard)) {// 如果是第一次打卡
					String sql1 = "update uf_zsws_jbdjb set card1=?  where sqr=? and jbrq=?";
					RecordSet rs1 = new RecordSet();
					rs1.executeUpdate(sql1, kqsj, curruserid, kqrq);

				}
				if ("card2".equals(dkcard)) {// 如果是第二次次打卡
					String sqlfirst = "select top 1* from uf_zsws_jbdjb where sqr=? and jbrq=? order by id desc ";
					RecordSet rsfirst = new RecordSet();
					rsfirst.executeQuery(sqlfirst, curruserid, kqrq);
					if (rsfirst.next()) {// 读取第一次打卡
						String card1 = rsfirst.getString("card1");
						String hjsqxss = rsfirst.getString("hjsqxss");// 申请小时数

						if (isNotEmpty(card1)) {
							BigDecimal hours = getTimeDifference(kqsj, card1);
							BigDecimal sqhours = new BigDecimal(hjsqxss);// 申请小时数
							if (hours.compareTo(sqhours) > 0) {// 如果加班计算出来的小时数>申请加班小时数，则取小原则
								hours = sqhours;
							}
							BigDecimal days = hours.multiply(BigDecimal.valueOf(0.125)).setScale(4,
									BigDecimal.ROUND_DOWN);
							String sql2 = "update uf_zsws_jbdjb set card2=?,hjsjxss=?,hjsjts=?  where sqr=? and jbrq=?";
							RecordSet rs2 = new RecordSet();
							rs2.executeUpdate(sql2, kqsj, hours, days, curruserid, kqrq);

							updateOrInsert(eid, name, days.toString());

						} else {
							String sql2 = "update uf_zsws_jbdjb set card2=?  where sqr=? and jbrq=?";
							RecordSet rs2 = new RecordSet();
							rs2.executeUpdate(sql2, kqsj, curruserid, kqrq);
						}

					}

				}
				if ("card3".equals(dkcard)) {// 如果是第三次打卡
					String sql3 = "update uf_zsws_jbdjb set card3=?  where sqr=? and jbrq=?";
					RecordSet rs3 = new RecordSet();
					rs3.executeUpdate(sql3, kqsj, curruserid, kqrq);
				}
				if ("card4".equals(dkcard)) {// 如果是第四次打卡
					String sqlfirst = "select top 1* from uf_zsws_jbdjb where sqr=? and jbrq=? order by id desc ";
					RecordSet rsfirst = new RecordSet();
					rsfirst.executeQuery(sqlfirst, curruserid, kqrq);
					if (rsfirst.next()) {// 读取第一次打卡
						String card3 = rsfirst.getString("card3");
						String hjsqxss = rsfirst.getString("hjsqxss");// 申请小时数
						String hjsjxss = rsfirst.getString("hjsjxss");// 上午实际加班的小时数
						if (isNotEmpty(card3)) {
							BigDecimal hours = getTimeDifference(kqsj, card3);
							BigDecimal sqhours = new BigDecimal(hjsqxss);// 申请小时数
							BigDecimal swsjhours = new BigDecimal(hjsjxss);// 上午实际加班的小时数
							BigDecimal allhours = hours.add(swsjhours); // 加上上午的加班数判断
							if (allhours.compareTo(sqhours) > 0) {// 如果上午加班+下午加班计算出来的小时数>申请加班小时数，则取小原则
								allhours = sqhours;
							}
							BigDecimal xwsjhours = allhours.subtract(swsjhours);// 下午实际加班有效的小时数
							BigDecimal xwdays = xwsjhours.multiply(BigDecimal.valueOf(0.125)).setScale(4,
									BigDecimal.ROUND_DOWN);
							BigDecimal days = allhours.multiply(BigDecimal.valueOf(0.125)).setScale(4,
									BigDecimal.ROUND_DOWN);

							String sql4 = "update uf_zsws_jbdjb set card4=?,hjsjxss=?,hjsjts=?  where sqr=? and jbrq=?";
							RecordSet rs4 = new RecordSet();
							rs4.executeUpdate(sql4, kqsj, allhours, days, curruserid, kqrq);

							updateOrInsert(eid, name, xwdays.toString());

						} else {
							String sql4 = "update uf_zsws_jbdjb set card4=?  where sqr=? and jbrq=?";
							RecordSet rs4 = new RecordSet();
							rs4.executeUpdate(sql4, kqsj, curruserid, kqrq);
						}

					}
				}
			}
		}
		return flag;
	}

	public static boolean updateOrInsert(String eid, String name, String days) {
		boolean flag = false;
		String sqlcheck = "select * from uf_zswsHRaBal_buxiu where eid=?";
		RecordSet rssqlcheck = new RecordSet();
		rssqlcheck.executeQuery(sqlcheck, eid);
		if (rssqlcheck.next()) {// 如果有记录
			String sqlbuxiudjb = " update   uf_zswsHRaBal_buxiu set expr1=isnull(CONVERT(decimal(15,4),expr1),0)+? where eid=?";
			RecordSet rssqlbuxiudjb = new RecordSet();
			flag = rssqlbuxiudjb.executeUpdate(sqlbuxiudjb, days, eid);
		} else {
			String insert = "insert into uf_zswsHRaBal_buxiu(eid,name,baltype,expr1)values(?,?,?,?)";
			RecordSet rsinsert = new RecordSet();
			flag = rsinsert.executeUpdate(insert, eid, name, 3, days.toString());
		}
		return flag;
	}

	/***
	 * @comments 计算两个时间的时间差(加班小时数)
	 * @param strTime1
	 * @param strTime2
	 */
	public static BigDecimal getTimeDifference(String strTime1, String strTime2) {
		BigDecimal hours = BigDecimal.ZERO;
		SimpleDateFormat df = new SimpleDateFormat("HH:mm");
		try {
			Date date1 = df.parse(strTime1);
			Date date2 = df.parse(strTime2);
			BigDecimal diff = BigDecimal.valueOf(date1.getTime() - date2.getTime()); // 获取时间差
			BigDecimal unit = BigDecimal.valueOf(60 * 60 * 1000);// 小时换算进制

			BigDecimal hourcalc = diff.divide(unit, 1, BigDecimal.ROUND_DOWN);// 舍模式保留1位小数
			int hour10 = hourcalc.multiply(BigDecimal.TEN).intValue();// 乘10转化为整数
			if (hour10 % 10 < 5) {// 如果不足半小时
				hours = BigDecimal.valueOf(hour10 / 10).setScale(1, BigDecimal.ROUND_DOWN);

			} else {// 超出半小时一律算0.5
				hours = BigDecimal.valueOf((hour10 / 10) + 0.5).setScale(1, BigDecimal.ROUND_DOWN);

			}
//			if (hours.compareTo(BigDecimal.valueOf(4)) > 0) {
//				hours = BigDecimal.valueOf(4).setScale(1);
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hours;
	}
	
	/**
	 * 	根据客户端传入的时间 yyyy-MM-dd HH:mm 判断其处于哪个打卡班次
	 * @param currentlist
	 * @param datetime
	 * @return
	 */
    public static int getCurrTimeOfBanci(List<Map<String, Object>> currentlist,String datetime,String userid) {
    	int currentBanciIndex=currentlist.size();//默认值index为数据组长度
		for (int i = 0; i < currentlist.size(); i++) {
			Map<String, Object> banci=currentlist.get(i);
			if (DateUtil.compare_date(datetime, banci.get("dkend").toString(),"yyyy-MM-dd HH:mm")<=0) {
				currentBanciIndex=i;
				Map<String, Object> map=currentlist.get(i);
				RecordSet rs=new RecordSet();
				String sql="select top 1* from uf_kqxx where dkcard=? and kqry=? and "
						+ "convert(datetime,concat(kqrq,' ',kqsj))>=convert(datetime,?) and convert(datetime,concat(kqrq,' ',kqsj))<=convert(datetime,?) order by id desc";
				rs.executeQuery(sql, map.get("card" ).toString(),userid,map.get("dkstart").toString(),map.get("dkend").toString());
				
				if (!rs.next()) {
					break;
				}
			}		
		}
    	return currentBanciIndex;
    }
    
	public static Map<String ,Object> getDayshowDK(String userid,String datetime){
		
		String date=DateUtil.dateString(DateUtil.StringToDate(datetime, "yyyy-MM-dd HH:mm"), "yyyy-MM-dd") ;
		
		Map<String, Object> currentPb=getDayPbNew(userid, date, datetime);
		List<Map<String, Object>> currentlist= (List<Map<String, Object>>) currentPb.get("jsontime");
		
		Map<String, Object> showmap=new HashMap<>();
		List<Map<String, Object>> showlist=new ArrayList<>();
		int currentBanciIndex=getCurrTimeOfBanci(currentlist, datetime,userid);
		int btnlocation=currentBanciIndex;
		for (int i = 0; i < currentlist.size(); i++) {
			Map<String, Object> show=new HashMap<>();
			Map<String, Object> map=currentlist.get(i);
			
			show.putAll(map);
			if (i<=currentBanciIndex) {
				
				RecordSet rs=new RecordSet();
				String sql="select top 1* from uf_kqxx where dkcard=? and kqry=? and "
						+ "convert(datetime,concat(kqrq,' ',kqsj))>=convert(datetime,?) and convert(datetime,concat(kqrq,' ',kqsj))<=convert(datetime,?) order by id desc";
				
				rs.executeQuery(sql, map.get("card" ).toString(),userid,map.get("dkstart").toString(),map.get("dkend").toString());
				
				if (rs.next()) {
					show.put("iscard",1);//已打卡
					show.put("dkcardstatus", rs.getString("dkcardstatus"));//打卡状态
					show.put("kqdd", rs.getString("kqdd"));
					show.put("kqlx", rs.getString("kqlx"));
					show.put("sbxb", rs.getString("sbxb"));
					show.put("kqsj", rs.getString("kqsj"));
					if(i==currentBanciIndex) {//如果当前时刻排班已打卡，则将打卡移动到下一个打卡班次
						btnlocation=currentBanciIndex+1;
					}
				}else {
					show.put("iscard",0);//没有打卡
					if(i==currentBanciIndex) {//如果当前时刻没有打卡，视为不确定
						show.put("iscard",-1);//不确定
					}
				}
			}else {
				show.put("iscard",-1);//不确定(未来)
			}
			
			showlist.add(show);
		}
		showmap.putAll(currentPb);
		showmap.put("jsontime", showlist);
		showmap.put("btnlocation", btnlocation);//打卡按钮位置
		showmap.put("currentBanciIndex", currentBanciIndex);//当前时间所在排班班次（0开始）
		return showmap;
	}
	
	
	/**
	 * 结合跨天打卡，跨天考勤的排班打卡显示逻辑
	 * 
	 * @param id
	 * @param date     //查询传入的日期 yyyy-MM-dd
	 * @param datetime //查询传入的时间 yyyy-MM-dd HH:mm
	 * @return
	 */
	public static Map<String, Object> getDayPbNew(String id, String date, String datetime) {

		// 查询昨、今、明的排班
		String datepre = DateUtil.datedayCalculateStr(DateUtil.StringToDate(date, "yyyy-MM-dd"), -1);
		String datenext = DateUtil.datedayCalculateStr(DateUtil.StringToDate(date, "yyyy-MM-dd"), 1);
		Map<String, Object> mappre = getDayPb(id, datepre);
		Map<String, Object> map = getDayPb(id, date);
		Map<String, Object> mapnext = getDayPb(id, datenext);

		// 正常情况返回当日打卡排班
		Map<String, Object> pbmap = map;

		List<Map<String, Object>> listpre = (List<Map<String, Object>>) mappre.get("jsontime");
		// 如果昨天有排班打卡，则去判断昨天排班最后一次的打卡班次的打卡截止时间(yyyy-MM-dd HH:Mm)
		if (listpre.size() > 0) {
			Map<String, Object> cardlast = (Map<String, Object>) listpre.get(listpre.size() - 1);
			String carddk = cardlast.get("dkend").toString();
			// 接收的查询时间<昨天排班打卡范围,返回昨日排班打卡
			if (DateUtil.compare_date(datetime, carddk, "yyyy-MM-dd HH:mm") == -1) {
				pbmap = mappre;
			}
		}
		List<Map<String, Object>> listnext = (List<Map<String, Object>>) mapnext.get("jsontime");
		// 如果明天有排班打卡，则去判断明天排班第一次的打卡班次的打卡开始时间(yyyy-MM-dd HH:Mm)
		if (listnext.size() > 0) {
			Map<String, Object> cardfirst = (Map<String, Object>) listnext.get(0);
			String carddk = cardfirst.get("dkstart").toString();
			// 接收的查询时间>明天排班打卡开始范围,返回明日排班打卡
			if (DateUtil.compare_date(datetime, carddk, "yyyy-MM-dd HH:mm") == 1) {
				pbmap = mapnext;
			}
		}
		return pbmap;
	}

	/**
	 * 获取对应日期的排班信息
	 * 
	 * @param id
	 * @param date
	 * @return 查询归档日期在事件开始日期之前的数据（相同类型最后一条有效数据）
	 */
	public static Map<String, Object> getDayPb(String id, String date) {
		Map<String, Object> pbmap = new HashMap<>();
		String sql = "select top 1* from uf_pbbdxx where  applicant =? and convert(date,changeDate,20) =? "
				+ "and convert(date,confirmdate,20)<=convert(date,datestart,20) order by id desc ";
		RecordSet rs = new RecordSet();
		boolean flag = rs.executeQuery(sql, id, date);

		if (flag && rs.next()) {
			String type = rs.getString("type");
			String applicant = rs.getString("applicant");
			String card1 = rs.getString("card1");
			String card2 = rs.getString("card2");
			String card3 = rs.getString("card3");
			String card4 = rs.getString("card4");
			String cardtimes = rs.getString("cardtimes");
			String changeDate = rs.getString("changeDate");
			String changepbday = rs.getString("changepbday");
			String confirmdate = rs.getString("confirmdate");
			String dateend = rs.getString("dateend");
			String datestart = rs.getString("datestart");
			String endT1 = rs.getString("endT1");
			String endT2 = rs.getString("endT2");
			String endT3 = rs.getString("endT3");
			String endT4 = rs.getString("endT4");
			String endTime = rs.getString("endTime");
			String remarks = rs.getString("remarks");
			String requestId = rs.getString("requestId");
			String scan1 = rs.getString("scan1");
			String scan2 = rs.getString("scan2");
			String scan3 = rs.getString("scan3");
			String scan4 = rs.getString("scan4");
			String shenqindate = rs.getString("shenqindate");
			String shift = rs.getString("shift");
			String startTime = rs.getString("startTime");
			String title = rs.getString("title");
			String xhours = rs.getString("xhours");
			String xtype = rs.getString("xtype");
			Pbzxx flowpbz = new Pbzxx(shift, title, scan1, card1, endT1, scan2, card2, endT2, scan3, card3, endT3,
					scan4, card4, endT4, xhours, cardtimes);
			switch (type) {
			case "0":// 请假
				List<Map<String, Object>> listmap0 = getCardTimeByPbz(id, date, flowpbz);

				pbmap.put("jsontime", listmap0);
				pbmap.put("shiftType", shift);
				pbmap.put("title", title);
				break;
			case "1":// 调休
				List<Map<String, Object>> listmap1 = getCardTimeByPbz(id, date, flowpbz);
				pbmap.put("jsontime", listmap1);
				pbmap.put("shiftType", shift);
				pbmap.put("title", title);
				break;
			case "2":// 休息日加班
				List<Map<String, Object>> listmap2 = getCardTimeByPbz(id, date, flowpbz);
				pbmap.put("jsontime", listmap2);
				pbmap.put("shiftType", shift);
				pbmap.put("title", title);
				break;
			case "3":// 外派
				List<Map<String, Object>> listmap3 = getCardTimeByPbz(id, date, flowpbz);
				pbmap.put("jsontime", listmap3);
				pbmap.put("shiftType", shift);
				pbmap.put("title", title);
				break;
			case "4":// 出差
				List<Map<String, Object>> listmap4 = getCardTimeByPbz(id, date, flowpbz);
				pbmap.put("jsontime", listmap4);
				pbmap.put("shiftType", shift);
				pbmap.put("title", title);
				
				pbmap.put("jsontime", new ArrayList<>());
				pbmap.put("shiftType", shift);
				pbmap.put("title", "出差");
				break;
			case "5":// 培训
				List<Map<String, Object>> listmap5 = getCardTimeByPbz(id, date, flowpbz);
				pbmap.put("jsontime", listmap5);
				pbmap.put("shiftType", shift);
				pbmap.put("title", title);
				break;
			case "6":// 平日加班
				List<Map<String, Object>> listmap6 = new ArrayList<>();// 平日加班特殊处理，追加在当前排班组后面

				if (isNotEmpty(card1)) {
					listmap6.add(getDkbc(id, date, card1, scan1, endT1, "card5", 0, date, date, date));
				}
				if (isNotEmpty(card2)) {
					listmap6.add(getDkbc(id, date, card2, scan2, endT2, "card6", 1, date, date, date));
				}
				if (isNotEmpty(card3)) {
					listmap6.add(getDkbc(id, date, card3, scan3, endT3, "card7", 0, date, date, date));
				}
				if (isNotEmpty(card4)) {
					listmap6.add(getDkbc(id, date, card4, scan4, endT4, "card8", 1, date, date, date));
				}
				pbmap.put("jsontime", listmap6);
				pbmap.put("shiftType", shift);
				pbmap.put("title", title);
				Pbzxx pbz = getPbzxx(id, date);
				if (pbz == null) {// 如果当天没有排班
					pbmap.put("jsontime", new ArrayList<>());
					pbmap.put("shiftType", "R");
					pbmap.put("title", "休息");
				} else {
					List<Map<String, Object>> listmap = getCardTimeByPbz(id, date, flowpbz);
					// listmap.addAll(listmap6);//追加加班排班，暂时不处理，以后再说
					pbmap.put("jsontime", listmap);
					pbmap.put("shiftType", pbz.getShift());
					pbmap.put("title", pbz.getTitle());
					pbmap.put("agroupTitle", pbz.getAgroupTitle());
					pbmap.put("groupID", pbz.getGroupID());
				}
				break;
			case "7":// 出差加班无需打卡

				pbmap.put("jsontime", new ArrayList<>());
				pbmap.put("shiftType", shift);
				pbmap.put("title", title);
				break;
				
			case "8":// 外勤休息日加班

				List<Map<String, Object>> listmap8 = getCardTimeByPbz(id, date, flowpbz);
				pbmap.put("jsontime", listmap8);
				pbmap.put("shiftType", shift);
				pbmap.put("title", title);
				pbmap.put("groupID", "65");
				pbmap.put("agroupTitle", "正常班制1");
				break;
			default:
				break;
			}
		} else {// 没有流程重新触发排班的，直接读取考勤排班的排班数据是
			Pbzxx pbz = getPbzxx(id, date);
			if (pbz == null) {// 如果当天没有排班
				pbmap.put("jsontime", new ArrayList<>());
				pbmap.put("shiftType", "R");
				pbmap.put("title", "休息");
			} else {
				List<Map<String, Object>> listmap = getCardTimeByPbz(id, date, pbz);
				pbmap.put("jsontime", listmap);
				pbmap.put("shiftType", pbz.getShift());
				pbmap.put("title", pbz.getTitle());
				pbmap.put("agroupTitle", pbz.getAgroupTitle());
				pbmap.put("groupID", pbz.getGroupID());
			}
		}
		pbmap.put("day",date);
		return pbmap;

	}

	/**
	 * 
	 * 将排班信息转化为考勤打卡所需要的json格式数据，并在打卡时间、 按查询的日期条件将打卡开关时间上拼接日期，显示当天的完整排班时段(yyyy-MM-dd
	 * HH:mm), 用于判断该天排班是否有跨天考勤和跨天打卡，返回list
	 * 
	 * @param id
	 * @param date
	 * @param pbz
	 * @return
	 */
	private static List<Map<String, Object>> getCardTimeByPbz(String id, String date, Pbzxx pbz) {
		List<Map<String, Object>> listmap = new ArrayList<>();
		String timedatedk1 = date;// 打卡日期
		if (isNotEmpty(pbz.getCard1())) {

			String startdatedk = timedatedk1;// 打卡扫描开日期
			String enddatedk = timedatedk1;// 打卡扫描关日期
			// 如果扫描开时间>打卡时间，说明打卡涉及到前一天打卡，得到打卡前一天的日期
			if (DateUtil.compare_date(pbz.getScan1(), pbz.getCard1(), "HH:mm:ss") == 1) {
				startdatedk = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk1, "yyyy-MM-dd"), -1);
			}
			// 如果扫描关时间<打卡时间，说明打卡涉及到跨下一天打卡，得到打卡日期下一天的日期
			if (DateUtil.compare_date(pbz.getEndT1(), pbz.getCard1(), "HH:mm:ss") == -1) {
				enddatedk = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk1, "yyyy-MM-dd"), 1);
			}

			listmap.add(getDkbc(id, date, pbz.getCard1(), pbz.getScan1(), pbz.getEndT1(), "card1", 0, startdatedk,
					enddatedk, timedatedk1));
		}
		String timedatedk2 = timedatedk1;// 打卡日期
		if (isNotEmpty(pbz.getCard2())) {

			// 若果打卡时间2<打卡时间1，则说明考勤2是下一天打卡考勤
			if (DateUtil.compare_date(pbz.getCard2(), pbz.getCard1(), "HH:mm:ss") == -1) {
				timedatedk2 = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk2, "yyyy-MM-dd"), 1);
			}
			String startdatedk = timedatedk2;
			String enddatedk = timedatedk2;
			// 如果扫描开时间>打卡时间，说明打卡涉及到前一天打卡，得到打卡前一天的日期
			if (DateUtil.compare_date(pbz.getScan2(), pbz.getCard2(), "HH:mm:ss") == 1) {
				startdatedk = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk2, "yyyy-MM-dd"), -1);
			}
			// 如果扫描关时间<打卡时间，说明打卡涉及到跨下一天打卡，得到打卡日期下一天的日期
			if (DateUtil.compare_date(pbz.getEndT2(), pbz.getCard2(), "HH:mm:ss") == -1) {
				enddatedk = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk2, "yyyy-MM-dd"), 1);
			}
			listmap.add(getDkbc(id, date, pbz.getCard2(), pbz.getScan2(), pbz.getEndT2(), "card2", 1, startdatedk,
					enddatedk, timedatedk2));
		}
		String timedatedk3 = timedatedk2;// 打卡日期
		if (isNotEmpty(pbz.getCard3())) {
			// 若果打卡时间3<打卡时间2，则说明考勤3是下一天打卡考勤
			if (DateUtil.compare_date(pbz.getCard3(), pbz.getCard2(), "HH:mm:ss") == -1) {
				timedatedk3 = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk3, "yyyy-MM-dd"), 1);
			}
			String startdatedk = timedatedk3;
			String enddatedk = timedatedk3;

			// 如果扫描开时间>打卡时间，说明打卡涉及到前一天打卡，得到打卡前一天的日期
			if (DateUtil.compare_date(pbz.getScan3(), pbz.getCard3(), "HH:mm:ss") == 1) {
				startdatedk = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk3, "yyyy-MM-dd"), -1);
			}
			// 如果扫描关时间<打卡时间，说明打卡涉及到跨下一天打卡，得到打卡日期下一天的日期
			if (DateUtil.compare_date(pbz.getEndT3(), pbz.getCard3(), "HH:mm:ss") == -1) {
				enddatedk = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk3, "yyyy-MM-dd"), 1);
			}
			listmap.add(getDkbc(id, date, pbz.getCard3(), pbz.getScan3(), pbz.getEndT3(), "card3", 0, startdatedk,
					enddatedk, timedatedk3));
		}
		String timedatedk4 = timedatedk3;// 打卡日期
		if (isNotEmpty(pbz.getCard4())) {

			// 若果打卡时间4<打卡时间3，则说明考勤3是下一天打卡考勤
			if (DateUtil.compare_date(pbz.getCard4(), pbz.getCard3(), "HH:mm:ss") == -1) {
				timedatedk4 = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk4, "yyyy-MM-dd"), 1);
			}
			String startdatedk = timedatedk4;
			String enddatedk = timedatedk4;

			// 如果扫描开时间>打卡时间，说明打卡涉及到前一天打卡，得到打卡前一天的日期
			if (DateUtil.compare_date(pbz.getScan4(), pbz.getCard4(), "HH:mm:ss") == 1) {
				startdatedk = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk4, "yyyy-MM-dd"), -1);
			}
			// 如果扫描关时间<打卡时间，说明打卡涉及到跨下一天打卡，得到打卡日期下一天的日期
			if (DateUtil.compare_date(pbz.getEndT4(), pbz.getCard4(), "HH:mm:ss") == -1) {
				enddatedk = DateUtil.datedayCalculateStr(DateUtil.StringToDate(timedatedk4, "yyyy-MM-dd"), 1);
			}
			listmap.add(getDkbc(id, date, pbz.getCard4(), pbz.getScan4(), pbz.getEndT4(), "card4", 1, startdatedk,
					enddatedk, timedatedk4));
		}
		return listmap;
	}

	/**
	 * 获取打卡班次
	 * 
	 * @param card
	 * @param scan
	 * @param endT
	 * @param      cardname//班次name
	 * @param sbxb 0上班1下班
	 * @return
	 */
	private static Map<String, Object> getDkbc(String id, String date, String card, String scan, String endT,
			String cardname, int sbxb, String dkstartdate, String dkenddate, String dktimedate) {
		Map<String, Object> map = new HashMap<>();
		map.put("time", mySubStr(card));// 去掉秒
		map.put("start", mySubStr(scan));
		map.put("end", mySubStr(endT));
		map.put("content", "(" + mySubStr(scan) + "-" + mySubStr(endT) + ")");
		map.put("card", cardname);
		map.put("sbxb", sbxb);

		map.put("dktime", dktimedate + " " + mySubStr(card));// 去掉秒
		map.put("dkstart", dkstartdate + " " + mySubStr(scan));
		map.put("dkend", dkenddate + " " + mySubStr(endT));

		boolean iswaiqing = iswqsq(id, date, cardname);
		map.put("iswaiqing", iswaiqing);
		return map;
	}

	// 查询排班组信息
	public static Pbzxx getPbzxx(String id, String date) {
		String sql = "select t.*,z.agroupTitle,z.groupID from hrmresource  h inner join uf_rypbxx z on h.outkey=z.eid and h.id=? and CONVERT(date,z.term,20)=? inner join uf_pbzxx t "
				+ "on z.shift=t.shift and (t.isdisabled='0' or t.isdisabled is null)";
		RecordSet rs = new RecordSet();
		rs.executeQuery(sql, id, date);
		Pbzxx pbz = null;
		while (rs.next()) {
			pbz = new Pbzxx();
			pbz.setShift(rs.getString("shift"));
			pbz.setTitle(rs.getString("title"));
			pbz.setCard1(rs.getString("card1"));
			pbz.setCard2(rs.getString("card2"));
			pbz.setCard3(rs.getString("card3"));
			pbz.setCard4(rs.getString("card4"));
			pbz.setScan1(rs.getString("scan1"));
			pbz.setScan2(rs.getString("scan2"));
			pbz.setScan3(rs.getString("scan3"));
			pbz.setScan4(rs.getString("scan4"));
			pbz.setEndT1(rs.getString("endT1"));
			pbz.setEndT2(rs.getString("endT2"));
			pbz.setEndT3(rs.getString("endT3"));
			pbz.setEndT4(rs.getString("endT4"));
			pbz.setXhours(rs.getString("Xhours"));
			pbz.setAgroupTitle(rs.getString("agroupTitle"));
			pbz.setGroupID(rs.getString("groupID"));
			pbz.setCardTimes(rs.getString("CardTimes"));
		}
		return pbz;
	}

	// 判断当次打卡有没有申请外勤
	private static boolean iswqsq(String id, String date, String cardname) {
		String sql = "select * from uf_wqsq where sqrid=? and sqrq=? and sqcard=?";
		RecordSet rs = new RecordSet();
		boolean flag = rs.executeQuery(sql, id, date, cardname);
		if (flag && rs.next()) {
			return true;
		}
		return false;
	}

	/// 判断打卡card是否有效
	private static boolean isNotEmpty(String card) {
		if (!StringUtils.isEmpty(StringUtils.trim(card)) && !"NULL".equalsIgnoreCase(StringUtils.trim(card))) {
			return true;
		}
		return false;
	}

	/// 将时间字符串 HH:mm:ss截取为HH:mm
	private static String mySubStr(String card) {
		if (card != null && StringUtils.trim(card).length() > 5) {
			card = StringUtils.trim(card).substring(0, 5);
		}
		return card;
	}

}
